﻿using Dapper;
using FDSQLAssistant.Extensions;
using FDSQLAssistant.Models;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using DbType = FDSQLAssistant.Models.DbType;

namespace FDSQLAssistant.Repositories
{
    public class ContextRepository
    {
        protected readonly Config _config;

        public ContextRepository(Config config)
        {
            if (config == null || config.ConnectionString.IsNullOrEmpty())
                throw new ArgumentNullException("config");
            _config = config;
        }

        public int ExecuteNoneQuery(string sql, object parameter)
        {
            using IDbConnection conn = _config.DbType == DbType.SqlServer
                ? new SqlConnection(_config.ConnectionString)
                : new MySqlConnection(_config.ConnectionString);
            return conn.Execute(sql, parameter);
        }

        public T ExecuteScalar<T>(string sql, object parameter)
        {
            using IDbConnection conn = _config.DbType == DbType.SqlServer
                ? new SqlConnection(_config.ConnectionString)
                : new MySqlConnection(_config.ConnectionString);
            return conn.ExecuteScalar<T>(sql, parameter);

        }

        public List<T> Query<T>(string sql, object parameter)
        {
            using IDbConnection conn = _config.DbType == DbType.SqlServer
                ? new SqlConnection(_config.ConnectionString)
                : new MySqlConnection(_config.ConnectionString);
            return conn.Query<T>(sql, parameter).ToList();
        }

        public T QueryFirst<T>(string sql, object parameter)
        {
            using IDbConnection conn = _config.DbType == DbType.SqlServer
                ? new SqlConnection(_config.ConnectionString)
                : new MySqlConnection(_config.ConnectionString);

            return conn.QueryFirst<T>(sql, parameter);
        }
    }
}
